package com.study.bootstudy.config;

import org.apache.tomcat.util.descriptor.LocalResolver;
import org.springframework.cglib.core.Local;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * @Author RenPu
 * @Date 2021/7/30 17:16
 * @Version 1.0
 * @Description: 自定义控制方法请求，分发的映射
 **/
@Configuration
public class MyConfig implements WebMvcConfigurer {

    /**
     * 设置自定义拦截器方法
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**")
                .excludePathPatterns("/","/login.html","/css/**","/js/**","/img/**","/login");
    }



    @Override
    public void addViewControllers(ViewControllerRegistry registry) {

        registry.addViewController("/msb").setViewName("hello");
        registry.addViewController("/login.html").setViewName("login");
    }


    //实现国际化页面的展示，根据点击的中文或者英文进行页面风格的转变

    //localResolver此方法，也是根据WebMvcAutoConfirgation类源码获取到的
    @Bean(name = "localeResolver")
    public LocaleResolver localeResolver() {
        return new NativeLocaleResolver();
    }


    protected static class NativeLocaleResolver implements LocaleResolver {

        @Override
        public Locale resolveLocale(HttpServletRequest request) {
            //1:获取语言类型
            String langue = request.getParameter("language");

            System.out.println("-----------------------" + langue);
            //2：获取是否有默认语言
            Locale aDefault = Locale.getDefault();

            //3：判断从请求获取的语言是否为空，不为空的时候将request的语言类型进行返回
            if (!StringUtils.isEmpty(langue)) {
                String[] stringList = langue.split("_");
                aDefault = new Locale(stringList[0], stringList[1]);

            }
            return aDefault;

        }

        @Override
        public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {

        }
    }
}
